package cc.minos.question.plugins
{
	import cc.minos.console.Console;
	import cc.minos.utils.StringUtil;
	import flash.text.TextField;
	
	/**
	 * ...
	 * FillIn 填空
	 * 0908 更新一个空格多个答案
	 * @author Minos
	 */
	
	public class FillInPlugin extends QuestionPlugin
	{
		public static const VERSION:Number = 1.0;
		public static const API:Number = 2.0;
		// textfield array
		protected var tfs:Array;
		
		public function FillInPlugin()
		{
			this.propName = "FillInPlugin";
			//this.acronym = "fillin";
			optionName = "a_$_txt";
		}
		
		// ----- protected methods ----- //
		
		override protected function init():void
		{
			super.init();
			tfs = [];
			
			for each( var o:Object in skin ) {
				if ( o && o is TextField && o.name.charAt(0) == "a" ) {
					o.text = ""
					tfs[ StringUtil.substringBySign(o.name) ] =  o;
				}
			}
			options = tfs.length;
		}
		
		// Public Methods //
		
		override public function activate():void
		{
			super.activate()
			for ( var i:int = 0 , len:int = tfs.length ; i < len ; i++ )
			{
				if ( tfs[ i ] )
					tfs[ i ].mouseEnabled = true;
			}
		}
		
		override public function cancel():void
		{
			super.cancel();
			for ( var i:int = 0 , len:int = tfs.length ; i < len ; i++ )
			{
				if ( tfs[ i ] )
					tfs[ i ].mouseEnabled = false;
			}
		}
		
		/**
		 *
		 * @return
		 */
		override public function check():Boolean
		{
			for ( var i:int = 0 , len:int = tfs.length ; i < len ; i++ )
			{
				if ( tfs[ i ] && !_check( i ) )
				{
					return false;
				}
			}
			return true;
		}
		
		/**
		 * 获取得分
		 */
		override public function get score():Number
		{
			_score = 0;
			if ( checkAll )
				return check() ? tScore : 0;
			
			for ( var i:int = 0 , len:int = tfs.length ; i < len ; i++ )
			{
				if ( tfs[ i ] && _check( i ) )
				{
					_score += ( tScore / len );
				}else if( tfs[i].text != '' )
				{
					Console.log( '答案错误: ' + answer[i] + ' - ' + tfs[i].text , this , 1 );
				}
			}
			return _score;
		}
		
		/**
		 * 0908 根据答案类型检查
		 * @param	i
		 * @return
		 */
		protected function _check( i:int ):Boolean
		{
			var txt:String = tfs[i].text;
			var ans:Object = answer[i];
			var b:Boolean = true;
			txt = StringUtil.trim( txt );
			//fill many
			if ( ans is Array )
			{
				if (( ans as Array ).indexOf( txt ) == -1 )
					b = false;
			}
			else
			{
				if ( StringUtil.trim( ans.toString() ) != txt )
					b = false;
			}
			return b;
		}
		
		/**
		 * 重置
		 */
		override public function reset():void
		{
			super.reset();
			for ( var i:int = 0 , len:int = tfs.length ; i < len ; i++ )
			{
				if ( tfs[ i ] )
					tfs[ i ].text = "";
			}
		}
		
		protected function getTextFiledByIndex( idx:int = 0 ):TextField
		{
			return (getChild( optionName.replace( "$" , idx ) ) as TextField);
		}
	
	}

}